package com.jf.docsify.servlet;

import java.io.IOException;
import java.util.Base64;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jf.docsify.common.utils.GitServerUtil;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.storage.file.WindowCacheConfig;

/**
 * Description:
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/28.1       chenwr    2022/7/28           Create
 * </pre>
 * @date 2022/7/28
 */
public class GitServlet extends org.eclipse.jgit.http.server.GitServlet {

    public GitServlet() {
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String authorization = req.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            res.setHeader("WWW-Authenticate", "BASIC realm=\"jf-docsify\"");
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        // 获取用户名密码
        String basic_ = new String(Base64.getDecoder().decode(authorization.replace("Basic ", "")));
        String[] split = basic_.split(":");
        String userName = split[0];
        String password = split[1];
        try {
            req.login(userName, password);
        } catch (Exception e) {
            String message = e.getMessage();
            if (StringUtils.isNotBlank(message) && message.indexOf("UT010031: Login failed") != -1) {
                res.setHeader("WWW-Authenticate", "BASIC realm=\"jf-docsify\"");
                res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
            e.printStackTrace();
            return;
        }
//        String pathInfo = req.getPathInfo();
//        if (pathInfo.indexOf(".git") != -1) {
//            pathInfo = pathInfo.replace(".git", "/.git");
//            req = new GitHttpServletRequestWrapper(req, pathInfo);
//        }
        super.service(req, res);
        GitServerUtil.reConfigWindowCache();
    }


}